// 引入Electron的ipcRenderer
const { ipcRenderer } = require('electron');

// 应用状态
class AppState {
    constructor() {
        this.localPath = '';
        this.remotePath = '/';
        this.selectedProvider = null;
        this.compareResult = null;
        this.isUploading = false;
        this.uploadProgress = null;
    }
}

const appState = new AppState();

// DOM元素引用
const elements = {
    localPath: document.getElementById('localPath'),
    selectLocalBtn: document.getElementById('selectLocalBtn'),
    remotePath: document.getElementById('remotePath'),
    providerCards: document.querySelectorAll('.provider-card'),
    compareBtn: document.getElementById('compareBtn'),
    uploadBtn: document.getElementById('uploadBtn'),
    comparePanel: document.getElementById('comparePanel'),
    uploadPanel: document.getElementById('uploadPanel'),
    configModal: document.getElementById('configModal'),
    modalClose: document.getElementById('modalClose'),
    configForm: document.getElementById('configForm'),
    saveConfigBtn: document.getElementById('saveConfigBtn'),
    testConnectionBtn: document.getElementById('testConnectionBtn'),
    modalTitle: document.getElementById('modalTitle'),
    messageContainer: document.getElementById('messageContainer')
};

// 初始化应用
function initializeApp() {
    setupEventListeners();
    loadProviderConfigs();
    updateUI();
}

// 设置事件监听器
function setupEventListeners() {
    // 选择本地目录
    elements.selectLocalBtn.addEventListener('click', selectLocalDirectory);
    
    // 远程路径输入
    elements.remotePath.addEventListener('input', (e) => {
        appState.remotePath = e.target.value || '/';
        updateUI();
    });
    
    // 云服务提供商选择
    elements.providerCards.forEach(card => {
        card.addEventListener('click', () => selectProvider(card.dataset.provider));
    });
    
    // 比较文件按钮
    elements.compareBtn.addEventListener('click', compareFiles);
    
    // 上传按钮
    elements.uploadBtn.addEventListener('click', startUpload);
    
    // 模态框关闭
    elements.modalClose.addEventListener('click', closeModal);
    elements.configModal.addEventListener('click', (e) => {
        if (e.target === elements.configModal) {
            closeModal();
        }
    });
    
    // 保存配置
    elements.saveConfigBtn.addEventListener('click', saveConfig);
    
    // 测试连接
    elements.testConnectionBtn.addEventListener('click', testConnection);
    
    // 监听上传进度
    ipcRenderer.on('upload-progress', (event, progress) => {
        updateUploadProgress(progress);
    });
}

// 选择本地目录
async function selectLocalDirectory() {
    try {
        const result = await ipcRenderer.invoke('select-local-directory');
        if (result) {
            appState.localPath = result;
            elements.localPath.value = result;
            updateUI();
            showMessage('本地目录选择成功', 'success');
        }
    } catch (error) {
        console.error('选择目录失败:', error);
        showMessage('选择目录失败: ' + error.message, 'error');
    }
}

// 选择云服务提供商
function selectProvider(provider) {
    // 移除之前的选中状态
    elements.providerCards.forEach(card => {
        card.classList.remove('selected');
    });
    
    // 添加选中状态
    const selectedCard = document.querySelector(`[data-provider="${provider}"]`);
    selectedCard.classList.add('selected');
    
    appState.selectedProvider = provider;
    updateUI();
    
    // 打开配置模态框
    openConfigModal(provider);
}

// 打开配置模态框
async function openConfigModal(provider) {
    const providerNames = {
        tencent: '腾讯云 COS',
        aliyun: '阿里云 OSS',
        bytedance: '字节云 TOS',
        aws: 'AWS S3'
    };
    
    elements.modalTitle.textContent = `${providerNames[provider]} 配置`;
    
    // 加载现有配置
    try {
        const config = await ipcRenderer.invoke('get-cloud-config', provider);
        if (config) {
            document.getElementById('accessKeyId').value = config.accessKeyId || '';
            document.getElementById('secretAccessKey').value = config.secretAccessKey || '';
            document.getElementById('region').value = config.region || '';
            document.getElementById('bucket').value = config.bucket || '';
            document.getElementById('endpoint').value = config.endpoint || '';
        } else {
            // 清空表单
            elements.configForm.reset();
        }
    } catch (error) {
        console.error('加载配置失败:', error);
        elements.configForm.reset();
    }
    
    elements.configModal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    elements.configModal.style.display = 'none';
}

// 保存配置
async function saveConfig() {
    const formData = new FormData(elements.configForm);
    const config = {
        provider: appState.selectedProvider,
        accessKeyId: document.getElementById('accessKeyId').value,
        secretAccessKey: document.getElementById('secretAccessKey').value,
        region: document.getElementById('region').value,
        bucket: document.getElementById('bucket').value,
        endpoint: document.getElementById('endpoint').value
    };
    
    // 验证必填字段
    if (!config.accessKeyId || !config.secretAccessKey || !config.region || !config.bucket) {
        showMessage('请填写所有必填字段', 'error');
        return;
    }
    
    try {
        const success = await ipcRenderer.invoke('save-cloud-config', config);
        if (success) {
            showMessage('配置保存成功', 'success');
            closeModal();
            loadProviderConfigs();
        } else {
            showMessage('配置保存失败', 'error');
        }
    } catch (error) {
        console.error('保存配置失败:', error);
        showMessage('保存配置失败: ' + error.message, 'error');
    }
}

// 测试连接
async function testConnection() {
    const config = {
        provider: appState.selectedProvider,
        accessKeyId: document.getElementById('accessKeyId').value,
        secretAccessKey: document.getElementById('secretAccessKey').value,
        region: document.getElementById('region').value,
        bucket: document.getElementById('bucket').value,
        endpoint: document.getElementById('endpoint').value
    };
    
    if (!config.accessKeyId || !config.secretAccessKey || !config.region || !config.bucket) {
        showMessage('请填写所有必填字段', 'error');
        return;
    }
    
    try {
        elements.testConnectionBtn.disabled = true;
        elements.testConnectionBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中...';
        
        // 这里应该调用后端的测试连接方法
        // 暂时模拟测试结果
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        showMessage('连接测试成功', 'success');
    } catch (error) {
        console.error('连接测试失败:', error);
        showMessage('连接测试失败: ' + error.message, 'error');
    } finally {
        elements.testConnectionBtn.disabled = false;
        elements.testConnectionBtn.innerHTML = '<i class="fas fa-plug"></i> 测试连接';
    }
}

// 加载云服务提供商配置状态
async function loadProviderConfigs() {
    const providers = ['tencent', 'aliyun', 'bytedance', 'aws'];
    
    for (const provider of providers) {
        try {
            const config = await ipcRenderer.invoke('get-cloud-config', provider);
            const statusElement = document.getElementById(`${provider}Status`);
            
            if (config) {
                statusElement.innerHTML = '<i class="fas fa-circle"></i> 已配置';
                statusElement.classList.add('configured');
            } else {
                statusElement.innerHTML = '<i class="fas fa-circle"></i> 未配置';
                statusElement.classList.remove('configured');
            }
        } catch (error) {
            console.error(`加载${provider}配置失败:`, error);
        }
    }
}

// 比较文件
async function compareFiles() {
    if (!appState.localPath || !appState.selectedProvider) {
        showMessage('请先选择本地目录和云服务提供商', 'error');
        return;
    }
    
    try {
        elements.compareBtn.disabled = true;
        elements.compareBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 比较中...';
        
        const result = await ipcRenderer.invoke('compare-files', 
            appState.localPath, 
            appState.remotePath, 
            appState.selectedProvider
        );
        
        appState.compareResult = result;
        displayCompareResult(result);
        updateUI();
        
        showMessage('文件比较完成', 'success');
    } catch (error) {
        console.error('文件比较失败:', error);
        showMessage('文件比较失败: ' + error.message, 'error');
    } finally {
        elements.compareBtn.disabled = false;
        elements.compareBtn.innerHTML = '<i class="fas fa-search"></i> 比较文件';
    }
}

// 显示比较结果
function displayCompareResult(result) {
    // 更新统计信息
    document.getElementById('newFilesCount').textContent = result.newFiles.length;
    document.getElementById('modifiedFilesCount').textContent = result.modifiedFiles.length;
    document.getElementById('unchangedFilesCount').textContent = result.unchangedFiles.length;
    document.getElementById('totalSize').textContent = formatFileSize(result.totalSize);
    
    // 显示文件列表
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = '';
    
    const allFiles = [
        ...result.newFiles.map(f => ({ ...f, status: 'new' })),
        ...result.modifiedFiles.map(f => ({ ...f, status: 'modified' })),
        ...result.unchangedFiles.map(f => ({ ...f, status: 'unchanged' }))
    ];
    
    allFiles.forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = `file-item ${file.status}`;
        fileItem.innerHTML = `
            <div class="file-name">${file.relativePath}</div>
            <div class="file-size">${formatFileSize(file.size)}</div>
        `;
        fileList.appendChild(fileItem);
    });
    
    elements.comparePanel.style.display = 'block';
}

// 开始上传
async function startUpload() {
    if (!appState.compareResult || !appState.selectedProvider) {
        showMessage('请先进行文件比较', 'error');
        return;
    }
    
    const filesToUpload = [
        ...appState.compareResult.newFiles,
        ...appState.compareResult.modifiedFiles
    ];
    
    if (filesToUpload.length === 0) {
        showMessage('没有需要上传的文件', 'warning');
        return;
    }
    
    const uploadConfig = {
        provider: appState.selectedProvider,
        localPath: appState.localPath,
        remotePath: appState.remotePath,
        files: filesToUpload
    };
    
    try {
        appState.isUploading = true;
        updateUI();
        
        elements.uploadPanel.style.display = 'block';
        
        const success = await ipcRenderer.invoke('start-upload', uploadConfig);
        
        if (success) {
            showMessage('上传完成', 'success');
        } else {
            showMessage('上传失败', 'error');
        }
    } catch (error) {
        console.error('上传失败:', error);
        showMessage('上传失败: ' + error.message, 'error');
    } finally {
        appState.isUploading = false;
        updateUI();
    }
}

// 更新上传进度
function updateUploadProgress(progress) {
    appState.uploadProgress = progress;
    
    document.getElementById('currentFile').textContent = progress.currentFile || '准备上传...';
    document.getElementById('fileProgress').textContent = `${progress.currentFileIndex}/${progress.totalFiles}`;
    document.getElementById('sizeProgress').textContent = `${formatFileSize(progress.uploadedSize)} / ${formatFileSize(progress.totalSize)}`;
    document.getElementById('uploadSpeed').textContent = `${formatFileSize(progress.speed)}/s`;
    document.getElementById('progressFill').style.width = `${progress.totalProgress}%`;
    document.getElementById('progressPercentage').textContent = `${Math.round(progress.totalProgress)}%`;
    
    if (progress.status === 'completed') {
        showMessage('上传完成', 'success');
        appState.isUploading = false;
        updateUI();
    } else if (progress.status === 'error') {
        showMessage(`上传错误: ${progress.error}`, 'error');
        appState.isUploading = false;
        updateUI();
    }
}

// 更新UI状态
function updateUI() {
    // 更新比较按钮状态
    elements.compareBtn.disabled = !appState.localPath || !appState.selectedProvider || appState.isUploading;
    
    // 更新上传按钮状态
    elements.uploadBtn.disabled = !appState.compareResult || appState.isUploading;
    
    // 更新上传按钮文本
    if (appState.isUploading) {
        elements.uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
    } else {
        elements.uploadBtn.innerHTML = '<i class="fas fa-upload"></i> 开始上传';
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageElement = document.createElement('div');
    messageElement.className = `message ${type}`;
    messageElement.textContent = message;
    
    elements.messageContainer.appendChild(messageElement);
    
    // 3秒后自动移除消息
    setTimeout(() => {
        if (messageElement.parentNode) {
            messageElement.parentNode.removeChild(messageElement);
        }
    }, 3000);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initializeApp);